package com.lagou.edu.filter;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.util.*;

/**
 * 防IP暴刷过滤器，这里做过滤，单个ip 1分钟内只允许100个以下的注册请求
 */
@Component
public class RegisterIpFilter implements GlobalFilter, Ordered {

    //用map来缓存登录的ip，这里简单实现，不考虑ip过多导致内存过大的风险
    private static Map<String, List<Date>> ipMap = new HashMap<>();

    @Value("${gateway.countRange}")
    private Integer countRange;

    @Value("${gateway.countSize}")
    private Integer countSize;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getPath().toString();
        //如果不是进入注册页面，不进行限制
        if(path.indexOf("/api/user/register") == -1){
           return chain.filter(exchange);
        }
        //获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();
        Date now = new Date();
        //第一次访问
        if(ipMap.get(clientIp) == null){
            List<Date> list = new ArrayList<>();
            list.add(now);
            ipMap.put(clientIp,list);
        }else{
            ipMap.get(clientIp).add(now);
        }
        //获得一分钟之前的时间
        Date oneMinuteBefore = DateUtils.addMinutes(now,-countRange);
        for(int i=0 ; i <ipMap.get(clientIp).size();i++){
            //超过一分钟的时间，就删除掉
            if(oneMinuteBefore.compareTo(ipMap.get(clientIp).get(i)) == -countRange){
                ipMap.get(clientIp).remove(ipMap.get(clientIp).get(i));
            }
        }
        int size = ipMap.get(clientIp).size();
        if(size > countSize){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "count 100 more,try again after.";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
